import {
  Button,
  Card,
  Col,
  Descriptions,
  DescriptionsProps,
  Empty,
  message,
  Row,
  Spin,
  Steps,
  Tabs,
  Timeline,
} from "antd";
import DOMPurify from "dompurify";
import { types } from "./const";
import { gutter } from "../const/keys";
import {
  EyeOutlined,
  PlusOutlined,
  SmallDashOutlined,
} from "@ant-design/icons";
import AddBaojiaDan from "./AddBaojiaDan";
import { useEffect, useState } from "react";
import { getSaleDetail, getSaleLogSimpleList } from "@/services/sale";
import { formatData } from "@/utils";
import Log from "./Log";

import ViewUserModal from "./ViewUserModal";
import styles from "./index.modules.less";
import { getQuotationList } from "@/services/quotation";
import BaojiaDan from "./BaojiaDan";

const App = () => {
  //获取URL /sale/detail/1014 ID 1014
  const id = window.location.pathname.split("/").pop();
  const [projectStage, setProjectStage] = useState<number>(0);
  const [detail, setDetail] = useState<any>({});
  const [viewUserOpen, setViewUserOpen] = useState(false);
  const [userId, setUserId] = useState<number>();
  const [open, setOpen] = useState(false);
  const [logId, setLogId] = useState<number>();
  const [logOpen, setLogOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [logList, setLogList] = useState<any[]>([]);
  const [logLoading, setLogLoading] = useState(false);
  const [isLoadEnd, setIsLoadEnd] = useState(false);
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize] = useState<number>(5);
  const [isEnd, setIsEnd] = useState(false);

  let addNewAdd = false;
  const items = types?.map((item) => {
    const title = item.label;
    return { title };
  });
  const fetchData = async () => {
    setLoading(true);
    const { data, success, msg } = await getSaleDetail(id as any);

    const { projectStage } = data || {};
    setIsEnd(projectStage === 7);
    if (success) {
      setProjectStage(projectStage);
      setDetail(data);
    } else {
      message.error(msg || "获取销售详情失败");
    }
    setLoading(false);
  };
  const fetchLogData = async () => {
    setLogLoading(true);
    const { data: logData } = await getSaleLogSimpleList({
      pageNum,
      pageSize,
      businessOpportunityId: id,
    });

    if (addNewAdd) {
      setLogList(logData || []);
      addNewAdd = false;
    } else {
      setLogList([...logList, ...(logData || [])]);
    }
    setIsLoadEnd((logData || []).length < pageSize);
    setLogLoading(false);
  };
  useEffect(() => {
    if (!id) {
      return;
    }
    fetchData();
  }, [id]);
  useEffect(() => {
    if (!id) {
      return;
    }
    fetchLogData();
  }, [id, pageNum, pageSize]);
  const dItems: DescriptionsProps["items"] = [
    {
      label: "项目名称",
      span: 1,
      children: formatData(detail.opportunityName),
    },
    {
      label: "项目地址",
      span: 1,
      children: formatData(detail.projectLocation),
    },
    {
      label: "负责人",
      span: 1,
      children: formatData(detail.projectLeaderUserName),
    },
    {
      label: "项目阶段",
      span: 1,
      children: formatData(types[detail.projectStage - 2]?.label),
    },
    {
      label: "成单概率",
      span: 1,
      children: `${detail.transactionProbability}%`,
    },
    {
      label: "预估合同额",
      span: 1,
      children: formatData(
        ((detail.estimatedContractAmount || 0) / 100).toFixed(2)
      ),
    },
    {
      label: "预计签约日期",
      span: 1,
      children: formatData(detail.expectedSigningTime),
    },
    {
      label: "备注",
      span: 2,
      children: formatData(detail.opportunityRemark),
    },
    {
      label: "项目相关成员",
      span: 3,
      children:
        detail.memberList?.length === 0
          ? formatData("")
          : detail.memberList?.map((member: any, index: number) => {
              const key = `${index} + ${member.associationText}`;
              return (
                <span key={key}>
                  {index ? "、" : ""}
                  {member.associationText || "未知姓名"}
                </span>
              );
            }),
    },
    {
      label: "客户干系人",
      span: 3,
      children:
        detail.customerList?.length === 0
          ? formatData("")
          : detail.customerList?.map((customer: any, index: number) => {
              const key = `${index} + ${customer.associationText}`;
              return (
                <Button
                  key={key}
                  size="small"
                  type="link"
                  onClick={() => {
                    setViewUserOpen(true);
                    setUserId(customer.associationId);
                  }}
                >
                  {customer.associationText || "未知姓名"}
                </Button>
              );
            }),
    },
  ];

  return (
    <>
      <Row gutter={[gutter, gutter]}>
        <Col span={24}>
          <Steps type="navigation" current={projectStage - 2} items={items} />
        </Col>
        <Col span={24}>
          <Row gutter={[gutter, gutter]}>
            <Col span={18}>
              <Row gutter={[gutter, gutter]}>
                <Col span={24}>
                  <Card
                    title="基础信息"
                    loading={loading}
                    extra={
                      isEnd ? null : (
                        <Button
                          disabled={isEnd}
                          onClick={() => {
                            setLogOpen(true);
                          }}
                          icon={<PlusOutlined />}
                          ghost
                          type="primary"
                          size="small"
                        >
                          项目阶段变更
                        </Button>
                      )
                    }
                  >
                    <Descriptions items={dItems} labelStyle={{ width: 100 }} />
                  </Card>
                </Col>
                <Col span={24}>
                  <BaojiaDan id={id as any} isEnd={isEnd} data={detail} />
                </Col>
              </Row>
            </Col>
            <Col span={6}>
              <Card
                title="相关日志"
                extra={
                  isEnd ? null : (
                    <Button
                      type="primary"
                      size="small"
                      ghost
                      disabled={isEnd}
                      icon={<PlusOutlined />}
                      onClick={() => {
                        setLogOpen(true);
                      }}
                    >
                      添加日志
                    </Button>
                  )
                }
              >
                <Spin spinning={logLoading}>
                  {logList?.length < 0 ? <Empty /> : null}
                  <Timeline
                    items={logList?.map((item) => {
                      return {
                        children: (
                          <Row gutter={[gutter, gutter]}>
                            <Col span={24}>
                              <Row justify={"space-between"}>
                                <Col>{item.createTime}</Col>
                                <Col>
                                  <Button
                                    size="small"
                                    icon={<EyeOutlined />}
                                    type="link"
                                    onClick={() => {
                                      setLogId(item.id);
                                      setLogOpen(true);
                                    }}
                                  ></Button>
                                </Col>
                              </Row>
                            </Col>
                            <Col span={24}>
                              <Card size="small">
                                <Row>
                                  <Col span={24}>
                                    <strong>操作人:</strong>
                                    {item.createBy}
                                  </Col>
                                  <Col span={24} className={styles.logContent}>
                                    {/* 显示HTML内容 */}
                                    <span
                                      dangerouslySetInnerHTML={{
                                        __html: DOMPurify.sanitize(
                                          item.logContent || ""
                                        ),
                                      }}
                                    />
                                  </Col>
                                </Row>
                              </Card>
                            </Col>
                          </Row>
                        ),
                      };
                    })}
                  />
                  <Row justify="center" style={{ marginTop: 16 }}>
                    <Col>
                      <Button
                        loading={logLoading}
                        disabled={isLoadEnd}
                        size="small"
                        type="link"
                        onClick={() => {
                          setPageNum(pageNum + 1);
                        }}
                      >
                        加载更多
                        <SmallDashOutlined />
                      </Button>
                    </Col>
                  </Row>
                </Spin>
              </Card>
            </Col>
          </Row>
        </Col>
      </Row>

      {logOpen ? (
        <Log
          logId={logId as any}
          data={detail}
          id={Number(id)}
          onClose={async (reflash) => {
            setLogOpen(false);
            setLogId(undefined);
            if (reflash) {
              //刷新页面
              setIsLoadEnd(false);

              fetchData();
              addNewAdd = true;
              setLogList([]);
              setPageNum(1);
              fetchLogData();
            }
          }}
        />
      ) : null}

      {viewUserOpen ? (
        <ViewUserModal
          customerList={detail.customerList}
          userId={userId as any}
          onClose={() => {
            setUserId(undefined);
            setViewUserOpen(false);
          }}
        />
      ) : null}
    </>
  );
};
export default App;
